﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRExtensions
{
    [Authorize]
    public class TenantMessageHub : Hub
    {
        IAuthUser _authUser;
        ICache _cache;
        ILogger<TenantMessageHub> _logger;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="authUser"></param>
        /// <param name="cache"></param>
        public TenantMessageHub(IAuthUser authUser, ICache cache, ILogger<TenantMessageHub> logger)
        {

            _authUser = authUser;
            _cache = cache;
            _logger = logger;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {



            _logger.LogDebug($"上线==》--{_authUser.Id},{_authUser.UserName}.{_authUser.DisplayName}");

            _cache.SetAsync($"chat_{_authUser.Id}", Context.ConnectionId);

            var chats = _cache.GetKeys($"chat_*").Result;
            _logger.LogDebug($"租户在线用户:{JSON.Serialize(chats)}");


            Clients.Client(this.Context.ConnectionId).SendAsync("getId", Context.ConnectionId);
            Clients.Client(this.Context.ConnectionId).SendAsync("welcome", "欢迎您！");


            Groups.AddToGroupAsync(Context.ConnectionId, $"tenant_{TenantContext.Tenant?.Id}");//租户组

            return base.OnConnectedAsync();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {

            _logger.LogDebug($"离线：==》{_authUser.Id},{_authUser.UserName},{_authUser.DisplayName}");
            _cache.RemoveAsync($"chat_{_authUser.Id}");

            Groups.RemoveFromGroupAsync(Context.ConnectionId, $"tenant_{TenantContext.Tenant?.Id}");
            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 这里的函数专门接收客户端发来的消息，并可转发给指定客户端。
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public Task Ping(long deviceId, int step)
        {

            var tid = _cache.Get($"chat_{0}")?.ToString() ?? "";
            return Clients.Client(tid).SendAsync("Ping", deviceId, step);
        }


    }
}
